package com.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
import java.util.StringJoiner;

/***
 * 消息队列发送组件
 *
 * @author Kevin
 *
 */
@Slf4j
@Component
public class MqSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 发送消息队列
     *
     * @param exchange   交换机名称
     * @param routingKey 队列名
     * @param message    队列消息对象
     */
    public void send(String exchange, String routingKey, final Object message) {
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
    }


    /**
     * 发送消息队列（避免重复消费的发送机制）
     *
     * @param exchange   交换机名称
     * @param routingKey 队列名
     * @param message    队列消息对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendNoRepeat(String exchange, String routingKey, final Object message) {
        String id = createRandString();
        sendNoRepeat(exchange, routingKey, message, id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void sendNoRepeat(String exchange, String routingKey, final Object message, String id) {
        log.info("进入sendById参数:exchange->{},routingKey->{},message->{},id->{}", exchange, routingKey, message, id);
        StringJoiner messageId = new StringJoiner("-");
        // 消息队列放入redis中
        messageId.add("mq").add("smt").add(routingKey).add(id);
        log.info("redisKey->{}", messageId.toString());


        // 增加消息id用于去重
        rabbitTemplate.convertAndSend(exchange, routingKey, message, (msg) -> {
            msg.getMessageProperties().setMessageId(messageId.toString());
            return msg;
        });

//        System.out.println(1 / 0);


    }


    /**
     * 随机生成消息ID（当前时间毫秒+随机5位数）
     *
     * @return
     */
    public static String createRandString() {
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * 8999999) + 1000000;// 获取6位随机数
        String orderNo = String.valueOf(System.currentTimeMillis()) + rannum;
        return orderNo;
    }


}
